package vcsn.ui.view;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import org.eclipse.swt.widgets.Composite;
import org.eclipse.ui.part.*;
import org.eclipse.jface.viewers.*;
import org.eclipse.swt.graphics.Image;
import org.eclipse.ui.*;
import org.eclipse.swt.SWT;

import vcsn.Config;
import vcsn.entities.CommitPatch;
import vcsn.utils.ExportImportHandler;

public class ReceivedPatchView extends ViewPart {
	protected TableViewer viewer;
	private static ReceivedPatchView instance = null;
	private PatchListProvider patchListProvider;
	
	public class PatchListProvider extends ArrayContentProvider {
		private List<CommitPatch> patchList;
		public void inputChanged(Viewer v, Object oldInput, Object newInput) {

		}
		public void dispose() {
		}
		@Override
		public CommitPatch[] getElements(Object parent) {
			patchList = ExportImportHandler.importCommitPatch(System.getProperty(Config.homeDirectoryNotation) + File.separator + Config.incomingCommitPatchListFile, "demoroject2");
			CommitPatch[] patchArr = new CommitPatch[patchList.size()];
			patchList.toArray(patchArr);
			return patchArr;
		}
	}
	
	class ViewLabelProvider extends LabelProvider implements ITableLabelProvider {
		public String getColumnText(Object obj, int index) {
			//return getText(obj);
			CommitPatch patch = ((CommitPatch)obj);
			String returnLabel = "Patch : " + patch.getPatchHash() + "; From : " +patch.getAuthor() + " at : "+patch.getBuildDate();
			return returnLabel;
		}
		public Image getColumnImage(Object obj, int index) {
			return getImage(obj);
		}
		public Image getImage(Object obj) {
			return PlatformUI.getWorkbench().
					getSharedImages().getImage(ISharedImages.IMG_OBJ_ELEMENT);
		}
	}
	
	class NameSorter extends ViewerSorter {
	}

	public ReceivedPatchView(){
		super();
		instance = this;
		patchListProvider = new PatchListProvider();
	}
	
	@Override
	public void createPartControl(Composite parent) {
		viewer = new TableViewer(parent, SWT.MULTI | SWT.H_SCROLL | SWT.V_SCROLL);
		viewer.setContentProvider(patchListProvider);
		viewer.setLabelProvider(new ViewLabelProvider());
		viewer.setSorter(new NameSorter());
		getSite().setSelectionProvider(viewer);
		viewer.setInput(getViewSite());
	}

	@Override
	public void setFocus() {
		viewer.getControl().setFocus();
	}
	
	public PatchListProvider getContentProvider(){
		return patchListProvider;
	}
	
	public static ReceivedPatchView getInstance(){
		return (instance != null) ? instance : null;
	}
}
